/*
 * ================================================================================变量定义区
 */
var optype          = ""; //定义操作类型为 create/update
var currentPage     = 1;//全局变量，当前页
var validateRules   = "";//校验规则
var isRepeat        = false;//groupId是否改变
/*
 * ================================================================================页面初始化函数
 */
var validator;
$(function()
{
	//获取隐藏的用户名
	var optionKey = $("#hiddenOptionKey").val().trim();
	var groupId   = $("#hiddenGroupId").val().trim();
	
	//判断点击类型
	if(optionKey && optionKey.length>0)
	{
		optype = "update";
		$("#pageName").empty().append("update systemDict");
	}
	else
	{
		optype = "create";
		
		$("#pageName").empty().append("create systemDict");

		$("#groupId").attr("disabled","disabled");
		
		if(groupId == null || !groupId) 
		{
			$("#groupId").removeAttr("disabled");
		}
	}
	
	//加载验证规则
	setRules();
	
	//启动验证
	validator = $("#systemDictForm").validate(validateRules);
	
});

/*
 * ================================================================================函数定义区
 * 
 */
/**
 * 设置验证规则
 */
function setRules()
{
	validateRules = 
	{
		rules: 
		{
			groupId:
			{
				required:true,
				groupIdMaxLength:true,
				remote:
				{
					type:"post",
					url:BASE_PATH+"/systemDictManagement/checkOptionKeyRepeat.do",
					async: false,
					data:
					{
						parammeters:function() 
						{
							return $("#optionKey").val().trim() + "," 
								 + $("#groupId").val().trim() + ","
								 + $("#oldGroupId").val().trim()+ ","
								 + $("#oldOptionKey").val().trim() + ","
								 + optype;
						}
		             }  
		        }
			},
			
			optionKey:
			{
				required:true,
				remote:
				{
					type:"post",
					url:BASE_PATH+"/systemDictManagement/checkOptionKeyRepeat.do",
					async: false,
					data:
					{
						parammeters:function() 
						{
							return $("#optionKey").val().trim() + "," 
								 + $("#groupId").val().trim() + ","
								 + $("#oldGroupId").val().trim()+ ","
								 + $("#oldOptionKey").val().trim() + ","
								 + optype;
						}
		             }  
		        },
		        optionKeyMaxLength:true
			},
			
			optionVal:
			{
				required:true,
				optionValMaxLength:true
			},
			
			optionOrder:
			{
				required:false,
				digits:true,
				max:99,
				min:1
			},
			
			optionDesc:
			{
				required:true,
				optionDescMaxLength:true
			},
		},
		
		messages:
		{
			groupId:
			{
				required:"请输入GROUP_ID",
				remote:jQuery.format("GROUP_ID或者OPTION_KEY重复,请重新输入"),
				groupIdMaxLength:jQuery.format("GROUP_ID过长,请重新输入")
			},
			
			optionKey:
			{
				required:"请输入OPTION_KEY",
				remote:jQuery.format("GROUP_ID或者OPTION_KEY重复,请重新输入"),
				optionKeyMaxLength:jQuery.format("OPTION_KEY过长,请重新输入")
			},
			
			optionVal:
			{
				required:"请输入OPTION_VAL"			
			},	
			
			optionOrder:
			{
				required:"请输入OPTION_ORDER",
				digits:"请输入整数",
				max:"不能大于99",
				min:"不能小于1"
			},	
			
			optionDesc:
			{
				required:"请输入OPTION_DESC"			
			}
		}
	};	
	
	//验证groupId长度是否符合要求
	$.validator.addMethod("groupIdMaxLength",function(value,element)
	{
		validator.resetForm();
		var isPass             = true;
		var optionKeyElement   = document.getElementById("optionKey");
		if (!validator.checkable(optionKeyElement) && (optionKeyElement.name in validator.submitted || !validator.optional(optionKeyElement)) ) 
		{
			isPass = validator.element(optionKeyElement);
		}
		
		if(!isPass)
		{
			$("#groupId").addClass("validate-input-error");

		} else {
			$("#groupId").removeClass("validate-input-error");
			$("div[for='groupId']").remove();
		}
		
		var name              = $("#groupId").val().trim();
		var totalLength       = checkStringLength(name);
		var result            = true;
		
		//判断长度是否大于数据库长度
		if(totalLength-32>0)
		{
			result = false;
		}
		
		return result;
	}
	,"GROUP_ID过长,请重新输入");
	
	//验证optionKey长度是否符合要求
	$.validator.addMethod("optionKeyMaxLength",function(value,element)
	{
		var name              = $("#optionKey").val().trim();
		var totalLength       = checkStringLength(name);
		var result            = true;
		var isPass            = true;

		var groupIdElement    = document.getElementById("groupId");
		if (!validator.checkable(groupIdElement) && (groupIdElement.name in validator.submitted || !validator.optional(groupIdElement)) ) 
		{
			isPass = validator.element(groupIdElement);
		}
		
		if(!isPass)
		{
			$("#optionKey").addClass("validate-input-error");

		} else {
			$("#optionKey").removeClass("validate-input-error");
			$("div[for='optionKey']").remove();
		}
		
		//判断长度是否大于数据库长度
		if(totalLength-32>0)
		{
			result = false;
		}
		
		return result;
	}
	,"OPTION_KEY过长,请重新输入");
	
	//验证optionVal长度是否符合要求
	$.validator.addMethod("optionValMaxLength",function(value,element)
	{
		var name              = $("#optionVal").val().trim();
		var totalLength       = checkStringLength(name);
		var result            = true;
		
		//判断长度是否大于数据库长度
		if(totalLength-128>0)
		{
			result = false;
		}
		
		return result;
	}
	,"OPTION_VAL过长,请重新输入");
	
	//验证optionDesc 长度是否符合要求
	$.validator.addMethod("optionDescMaxLength",function(value,element)
	{
		var name              = $("#optionDesc").val().trim();
		var totalLength       = checkStringLength(name);
		var result            = true;
		
		//判断长度是否大于数据库长度
		if(totalLength-128>0)
		{
			result = false;
		}
		
		return result;
	}
	,"OPTION_DESC过长,请重新输入");
}

/**
 * 获取输入字符串的unicode长度
 * @param name 输入的字符串
 * @returns totalLength 字符串的unicode长度
 */
function checkStringLength(name)
{
	var totalLength   = 0;
	var charCode      = 0; 
	
	for (var i = 0; i < name.length; i++) 
	{ 
		charCode = name.charCodeAt(i);
		
		if (charCode < 0x007f) 
		{ 
			totalLength = totalLength + 1; 
		} 
		else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) 
		{ 
			totalLength += 2; 
		}
		else if ((0x0800 <= charCode) && (charCode <= 0xffff))
		{ 
			totalLength += 3; 
		} 
	} 
	return totalLength;
}

/**
 * submit
 */
function submitData()
{
	//提交时再进行验证
	var validateResult = $("#systemDictForm").validate(validateRules).form();
	//判断验证是否通过
	if(!validateResult) 
	{
		openAlert("请按提示输入完整信息");
		return;
	}
	else
	{
		var oldGroupId    = $("#oldGroupId").val().trim();
		var groupId       = $("#groupId").val().trim();
		var isChange      = groupIdIsChange();
		
		//判断组名是否发生了变化
		if(oldGroupId != groupId && optype == "update")
		{
			openConfirm('组名被修改，此组下所有记录的组名都会被统一更新，确定更新吗？', null, function() 
			{
				confirmSubmitData();
			});
		}
		else if(isChange && optype == "create") 
		{
			openConfirm('输入的组名数据库中已存在，记录会新增至以前组中，是否确认？', null, function() 
			{
				confirmSubmitData();
			});
		}
		else
		{
			confirmSubmitData();
		}
	}
}

/**
 * confirmSubmitData
 */
function confirmSubmitData()
{
	var groupId         = $("#groupId").val().trim();
	var optionKey       = $("#optionKey").val().trim();
	var optionVal       = $("#optionVal").val().trim();
	var optionOrder     = $("#optionOrder").val().trim();
	var optionDesc      = $("#optionDesc").val().trim();
	var createUser      = $("#singleIdHidden").attr("value").trim();
	var lastModifyUser  = $("#singleIdHidden").attr("value").trim();
	var oldOptionKey    = $("#oldOptionKey").val().trim();
	var oldGroupId      = $("#oldGroupId").val().trim();
	
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/systemDictManagement/addOrUpdateSystemDict.do',
        dataType:"json",       
		data:
		{
			"groupId"                 :  groupId,
			"optionKey"               :  optionKey,
			"optionVal"               :  optionVal,
			"optionOrder"             :  optionOrder,
			"optionDesc"              :  optionDesc,
			"createUser"              :  createUser,
			"lastModifyUser"          :  lastModifyUser,
			"optype"                  :  optype,
			"oldOptionKey"            :  oldOptionKey,
			"oldGroupId"              :  oldGroupId
		},
		success : function(data) 
		{
			if(data=='success')
			{
				openAlert('保存成功',function()
				{
					backToCurrentPage();
				});
			}
			else
			{
				openAlert(data);
			}
			
		},
		error:function(e)
		{
			openAlert('操作失败！错误信息：<div>'+e.responseText+"</div>");
		}
	});
}

/**
 * 在添加时判断输入的groupId是否改变，如果改变，则判断
 * 该groupId是否已经存在
 */
function groupIdIsChange() 
{
	//获取原本的optionKey的值
	var oldGroupId = $("#oldGroupId").val().trim();
	
	//获取提交时的optionKey的值
	var nowGroupId = $("#groupId").val().trim();
	
	if(oldGroupId != nowGroupId) 
	{
		$.ajax(
		{
			type: 'POST',
	        url: BASE_PATH +'/systemDictManagement/checkGroupIdRepeat.do',
	        dataType:"json", 
	        async:false,
			data:
			{
				"groupId"             :  nowGroupId
			},
			success : function(data) 
			{
				isRepeat = data;
			},
			error:function(e)
			{
				openAlert('操作失败！错误信息：<div>'+e.responseText+"</div>");
			}
		});
	}
	return isRepeat;
}

/**
 * cancel button
 */
function cancel()
{
	
	openConfirm('确定取消吗？', null, function() 
	{
		backToCurrentPage();
	});
}

/**
 * 返回当前页
 */
function backToCurrentPage()
{
	$("#submitcurrentpage").submit();
}
